/**
 * Copyright (C) 2017-2018 pinganfang, Inc. All Rights Reserved.
 */
package com.pingan.haofang.searchcloud.solr.api.client;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.pingan.haofang.searchcloud.api.client.ClientFactory;
import com.pingan.haofang.searchcloud.api.matedata.IndexMeta;
import com.pingan.haofang.searchcloud.api.matedata.IndexMetadataHolder;
import com.pingan.haofang.searchcloud.api.matedata.IndexMetadataHolderFactory;

/**
 * @author huhailiang937
 * @date 2017年7月5日下午8:40:09
 * @since 1.0.0
 */
@Component("solrClientFactory")
public class SolrClientFactory implements ClientFactory<CloudSolrClient> {

    protected static Logger LOG = LoggerFactory.getLogger(SolrClientFactory.class);

    private static final ConcurrentHashMap<String, CloudSolrClient> clientMap = new ConcurrentHashMap<String, CloudSolrClient>();

    @Override
    public CloudSolrClient getByName(String indexName) throws Exception {
        IndexMetadataHolder metadataHolder = IndexMetadataHolderFactory.get();
        IndexMeta meta = metadataHolder.findIndexMeta(indexName);
        if (null == meta) {
            return null;
        }
        String host = meta.getHost();
        return getByHost(host);
    }

    @Override
    public CloudSolrClient getByHost(String zkHosts) throws RuntimeException {

        CloudSolrClient client = clientMap.get(zkHosts);
        if (null != client) {
            return client;
        }
        CloudSolrClient.Builder builder = new CloudSolrClient.Builder();
        builder.withZkHost(zkHosts);
        client = builder.build();
        client.connect();

        clientMap.put(zkHosts, client);

        return client;
    }

}
